/* eslint-disable react/sort-comp */
/* eslint-disable react/destructuring-assignment */
/**
 * 和antd.form 关联起来
 */
import React from 'react';
import { Tooltip, Input } from 'antd';
import PropTypes from 'prop-types';

import FItem from '../WrapItem';

const showTip = (label) => {
  if (!label) return null;
  return <Tooltip title={label}>{label}</Tooltip>;
};

const TypeEnums = {
  Input: 'Input',
  TextArea: 'TextArea',
  Select: 'Select',
  Checkbox: 'Checkbox',
  CheckboxGroup: 'CheckboxGroup',
  RadioGroup: 'RadioGroup',
  InputNumber: 'InputNumber',
  DatePicker: 'DatePicker',
  MonthPicker: 'MonthPicker',
  RangePicker: 'RangePicker',
  WeekPicker: 'WeekPicker',
  InputLookUp: 'InputLookUp',
};

export default (Ele, type) => {
  return class FormComponent extends React.PureComponent {
    static propType = {
      rules: PropTypes.array,
      initialValue: PropTypes.object,
      hidden: PropTypes.bool,
      fieldOptions: PropTypes.object,
      formItemProps: PropTypes.object,
      options: PropTypes.object,
    };

    // 声明需要使用的Context属性
    static contextTypes = {
      form: PropTypes.object,
      params: PropTypes.object,
    };

    static defaultProps = {
      rules: [{ required: false, message: '必填' }], // 校验规则
      initialValue: undefined, // Form输入框初始值，可以通过form.setFieldsValue 来代替
      hidden: false, // 隐藏但是不消失
      fieldOptions: {}, // getFieldDecorator.options
      formItemProps: {},
      options: {}, // 输入标签属性
    };

    constructor(props) {
      super(props);
      const { form, id, label } = props;
      this.id = id;
      this.label = showTip(label); // 如果包含国际化就在这里处理一下
      this.type = type;
    }

    render() {
      const {
        rules, // 校验规则
        initialValue, // Form输入框初始值，可以通过form.setFieldsValue 来代替
        hidden, // 隐藏但是不消失
        fieldOptions, // getFieldDecorator.options
        formItemProps,
        options, // 输入标签属性
        form,
        extra,
        labelOptions,
        ...otherProps // FItem 属性 labelOptions
      } = this.props;

      const { getFieldDecorator } = form || this.context.form;

      // 隐藏字段
      if (hidden) {
        return getFieldDecorator(this.id, { initialValue, ...fieldOptions })(
          <Input hidden {...options} />
        );
      }

      return (
        <FItem {...formItemProps} {...labelOptions} extra={extra} label={this.label}>
          {getFieldDecorator(this.id, {
            rules,
            initialValue,
            ...fieldOptions,
          })(<Ele {...otherProps} {...options} />)}
        </FItem>
      );
    }
  };
};
